/*年轻人，只管向前看，不要管自暴自弃者的话*/
package com.composetest.page.main

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.composetest.page.cart.CartRoute
import com.composetest.page.home.HomeRoute
import com.composetest.page.me.MeRoute
import com.composetest.page.video.VideoRoute
import com.composetest.ui.component.MyNavigationBar
import com.composetest.ui.theme.ComposeTestTheme
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.launch

/**
 * create by itz on 2024/10/10 15:59
 * desc :
 **/

@Composable
fun MainRoute(toProductDetail: (String) -> Unit) {
    MainScreen(toProductDetail = toProductDetail)
}

@OptIn(ExperimentalPagerApi::class)
@Composable
fun MainScreen(toProductDetail: (String) -> Unit = {}) {
    // 当前选择的tab名称
    var currentDestination by remember {
        mutableStateOf(TopLevelDestination.HOME.route)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Gray)
    ) {

        val pagerState = rememberPagerState()
        val scope = rememberCoroutineScope()

        HorizontalPager(
            count = TopLevelDestination.values().size,
            state = pagerState,
            userScrollEnabled = false,
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
        ) { page ->
            when (page) {
                0 -> HomeRoute(toProductDetail = toProductDetail)
                1 -> VideoRoute()
                2 -> CartRoute()
                3 -> MeRoute()
            }
        }

        MyNavigationBar(
            destinations = TopLevelDestination.values().toList(),
            onNavigationToDestination = {
                currentDestination = TopLevelDestination.values()[it].route
                scope.launch { pagerState.scrollToPage(page = it) }
            },
            currentDestination = currentDestination,
            modifier = Modifier
        )
    }

}

@Preview
@Composable
fun MainScreenPreview() {
    ComposeTestTheme {
        MainScreen()
    }
}